package cn.fintecher.pangolin.service.dataimp.task;

import cn.fintecher.pangolin.common.enums.TaskBoxStatus;
import cn.fintecher.pangolin.common.enums.TaskBoxType;
import cn.fintecher.pangolin.common.model.TaskBoxModel;
import cn.fintecher.pangolin.common.model.UploadFile;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.mysql.CaseInfo;
import cn.fintecher.pangolin.service.dataimp.service.BaseService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 17:44 2019/10/19
 */

@Service("exportDistributeTask")
public class ExportDistributeTask {
    private static final Logger log = LoggerFactory.getLogger(ExportDistributeTask.class);

    @Autowired
    private BaseService baseService;

    /**
     * 分案导出
     */
    @Async
    public void exportDistribute(List<CaseInfo> caseInfos, UploadFile uploadFile, TaskBoxModel model, UserModel userModel) {
        if (caseInfos.isEmpty()) {
            String fileId = baseService.generateTxt(Collections.singletonList("分案导出没有数据"), Long.toString(new Date().getTime()));
            baseService.sendTaskBoxMessage(model, TaskBoxType.EXPORT, TaskBoxStatus.FAILURE, fileId, "分案导出", userModel, null, ZWDateUtil.getNowDateTime(), "分案导出");
        } else {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = baseService.getFile(uploadFile.getId());
                //复制一份模板
                File file = new File(baseService.filePath + "/" + DateTime.now().toDate().getTime() + ".xlsx");
                baseService.copyFile(in, file);
                InputStream inputStream = new FileInputStream(file);
                XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
                XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
                int rowNum = 1;
                for (CaseInfo caseInfo : caseInfos) {
                    Row row = sheet.createRow(rowNum);
                    for (int i = 0; i < 11; i++) {
                        Cell cell = row.createCell(i);
                        writeData(cell, i, caseInfo);
                    }
                    rowNum++;
                }
                out = new FileOutputStream(file);
                xssfWorkbook.write(out);
                UploadFile uploadFile1 = baseService.uploadExcel(file);
                baseService.sendTaskBoxMessage(model, TaskBoxType.EXPORT, TaskBoxStatus.FINISHED, uploadFile1.getId(), uploadFile1.getFileName(), userModel, null, ZWDateUtil.getNowDateTime(), "分案导出");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                String fileId = baseService.generateTxt(Collections.singletonList("分案导出异常"), Long.toString(new Date().getTime()));
                baseService.sendTaskBoxMessage(model, TaskBoxType.EXPORT, TaskBoxStatus.FAILURE, fileId, "分案导出异常", userModel, null, ZWDateUtil.getNowDateTime(), "分案导出");
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 写入数据
     */
    private void writeData(Cell cell, int i, CaseInfo caseInfo) {
        switch (i) {
            case 0:
                cell.setCellValue(caseInfo.getBatchNumber());
                break;
            case 1:
                cell.setCellValue(caseInfo.getCaseNumber());
                break;
            case 2:
                cell.setCellValue(caseInfo.getPersonalName());
                break;
            case 3:
                cell.setCellValue(caseInfo.getCertificateNo());
                break;
            case 4:
                cell.setCellValue(caseInfo.getPhone());
                break;
            case 5:
                cell.setCellValue(caseInfo.getCardNo());
                break;
            case 6:
                cell.setCellValue(caseInfo.getCity());
                break;
            case 7:
                cell.setCellValue(caseInfo.getOverdueAmtTotal());
                break;
            case 8:
                cell.setCellValue(caseInfo.getLeftAmt());
                break;
            case 9:
                cell.setCellValue(caseInfo.getCurrentCollector().getUsername());
                break;
            case 10:
                cell.setCellValue(caseInfo.getCurrentCollector().getRealName());
                break;
        }
    }
}
